
package com.liwt.algorithm;

/**
 * 求一个数组中的连续字数组的乘积最大的字数组
 * 
 * @author likebamboo
 * @create 2013-10-22
 * @see http://www.cnblogs.com/shirley130912/p/3362484.html
 */
public class MaxMulArr {
    public static double maxMul(double[] num) {
        int len = num.length;
        if (num == null || len < 1) {
            return 0;
        }

        double max = num[0];
        double maxSofar = num[0];
        double minSofar = num[0];
        for (int i = 1; i < len; ++i) {
            if (maxSofar > 1) {
                maxSofar *= num[i];
            } else {
                maxSofar = num[i];
            }
            // 重要的是如下这部分代码：暂时不知道为什么这么做-------------
            minSofar *= num[i];
            if (maxSofar < minSofar) {
                double tmp = maxSofar;
                maxSofar = minSofar;
                minSofar = tmp;
            }
            // /----------------------------------------
            if (maxSofar > max) {
                max = maxSofar;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        double[] num = {
                -3, -2, -4, 0, 5, -3, 8, 0, -12, 5, -3,
        };
        System.out.println(maxMul(num));
    }
}
